package icu.zlz.emqx.service.impl;

import icu.zlz.common.core.exception.ServiceException;
import icu.zlz.common.core.web.domain.AjaxResult;
import icu.zlz.emqx.domain.*;
import icu.zlz.emqx.mapper.IotDevicesTopicMapper;
import icu.zlz.emqx.mapper.IotGroupMapper;
import icu.zlz.emqx.mapper.IotTopicMapper;
import icu.zlz.emqx.service.IIotDevicesTopicService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zangsheng
 */
@Service
public class IotDevicesTopicServiceImpl implements IIotDevicesTopicService {
    @Resource
    private IotDevicesTopicMapper iotDevicesTopicMapper;

    @Resource
    private IotTopicMapper iotTopicMapper;
    @Resource
    private MqttAuthService mqttAuthService;

    @Transactional
    @Override
    public void batchContacts(IotGroup iotGroup, IotDevices iotDevices) {
        if (CollectionUtils.isEmpty(iotDevices.getIotDevicesTopicList())) {
            return;
        }
        iotDevicesTopicMapper.deleteIotDevicesTopicByDevicesIds(new Long[]{iotDevices.getDeviceId()});
        List<MqttAcl> mqttAclList = new ArrayList<>();
        List<IotDevicesTopic> iotDevicesTopicList = iotDevices.getIotDevicesTopicList();
        for (IotDevicesTopic iotDevicesTopic : iotDevicesTopicList) {
            iotDevicesTopic.setDeviceId(iotDevices.getDeviceId());
            MqttAcl mqttAcl = new MqttAcl();
            mqttAcl.setClientId(iotDevices.getDeviceClientId());
            mqttAcl.setPermission(iotDevicesTopic.getPermission());
            mqttAcl.setAction(iotDevicesTopic.getAction());
            IotTopic iotTopic = iotTopicMapper.selectIotTopicByTopicId(iotDevicesTopic.getTopicId());
            mqttAcl.setTopic(iotTopic.getTopicName());
            mqttAcl.setTopicUid(iotTopic.getUid());
            mqttAclList.add(mqttAcl);
        }
        iotDevicesTopicMapper.batchContacts(iotDevicesTopicList);
        mqttAuthService.deleteAclByClientIds(new String[]{iotDevices.getDeviceClientId()});
        AjaxResult ajaxResult = mqttAuthService.addAcl(iotGroup.getUid(), mqttAclList);
        if (!ajaxResult.isSuccess()) {
            throw new ServiceException("添加规则失败:" + ajaxResult.get(AjaxResult.MSG_TAG));
        }
        //


    }


    public List<IotDevicesTopic> selectIotDevicesTopicByDeviceId(Long deviceId) {
        return iotDevicesTopicMapper.selectIotDevicesTopicByDeviceId(deviceId);
    }
}
